//
//  GuideViewController.swift
//  demo
//
//  Created by mysj on 16/7/20.
//  Copyright © 2016年 zeng. All rights reserved.
//

import UIKit

//import SnapKit

class GuideViewController: UIViewController {
    
    
    
    var did = false
    
    override func animationDidStart(anim: CAAnimation) {
       
            
            self.titleLbl.alpha   = 0
            self.g_imgBgtp.alpha  = 0
            self.g_imgBgbm.alpha  = 0
            self.bgeinBtn.alpha   = 0
     
        
        print("start")
    }
    
    override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
        
       
            
            self.bgeinBtn.alpha   = 1
            self.g_imgBgtp.alpha  = 1
            self.g_imgBgbm.alpha  = 1
            self.titleLbl.text    = ""
            self.titleLbl.alpha   = 1
  
        
        print("stop")
    }
    
    let v = UIView(frame: CGRect(origin: CGPoint(x: -ScreenWidth, y: 0 ), size: ScreenSize))
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        //        generateSuitImages("/Users/mysj/Desktop/通信副本/IM", isA3x: false)
 
        
        //        self.navigationController?.navigationBar.hidden = true
        //        UIApplication.sharedApplication().keyWindow?.backgroundColor = UIColor.blackColor()
        //
        //        v.backgroundColor = UIColor.greenColor()
        //
        //        //        v.transform = CGAffineTransformMakeTranslation(-self.view.width , 0)
        //
        //        if did {
        //            UIView.animateWithDuration(0.5) {
        //                self.view.transform = CGAffineTransformIdentity
        //            }
        //            did = false
        //            return
        //        }
        //
        //
        //        UIView.animateWithDuration(0.5) {
        //            self.view.transform = CGAffineTransformMake(1, 0, 0, 1, self.view.width * 0.4, 11)
        //            self.view.layer.cornerRadius = 5
        //            self.view.layer.shadowColor  = UIColor.redColor().CGColor
        //            self.view.layer.shadowOffset = CGSizeMake(-10, 5)
        //            self.view.layer.shadowOpacity = 0.2
        //            self.view.layer.shadowRadius  = 4
        //            self.v.x += -2
        //            self.did = true
        //        }
        //
    }
    
    enum MoveDirection {
        case kNone;
        case kUp;
        case kDown;
        case kRight;
        case kLeft;
    }
    
    var direction:MoveDirection = .kNone
    
    let gestureMinimumOffset = 20.0
    
    func getDirection(translation: CGPoint) -> MoveDirection {
        if  Double(fabs(translation.x)) > gestureMinimumOffset {
            
            var iSHorizontal = false
            iSHorizontal = translation.y == 0 ? true: (fabs(translation.x / translation.y) > 5.0 )
            
            if iSHorizontal {
                return translation.x > 0.0 ? .kRight: .kLeft
            }
            
        } else if Double(fabs(translation.y)) > gestureMinimumOffset {
            
            var iSVertical = false
            iSVertical = translation.x == 0.0 ? true: (fabs(translation.y / translation.x) > 5.0 )
            
            if iSVertical {
                return translation.y > 0.0 ? .kDown: .kUp
            }
        }
        return .kUp
    }
    
    var animatingDrawer = false
    
    @objc private func panGestureCallback(pan: UIPanGestureRecognizer) {
        
        let translatedPoint = pan.translationInView(self.view)
        let of = translatedPoint.x
        
        switch pan.state {
        case .Began:
            if animatingDrawer {
                animatingDrawer = false
                pan.enabled = false
                UIView.animateWithDuration(0.5, animations: {
                    self.view.x = 0
                })
            } else {
                animatingDrawer = true
            }
            break
        case .Changed:
            self.view.userInteractionEnabled = false
            if getDirection(translatedPoint) == .kRight {
                UIView.animateWithDuration(0.1, animations: {
                    self.view.x = of < 200 ? of: 200
                })
            }
            
            break
        case .Ended, .Cancelled:
            if of < 200 {
                UIView.animateWithDuration(0.3, animations: {
                    self.view.x = 200
                })
            }
            self.view.userInteractionEnabled = true
            pan.enabled = true
            break
        default:
            break
        }
        
    }
    
    @objc private func newPageButtonClick(btn: UIButton) {
        
        
        
        let animation = CATransition()
        animation.duration = 2
        animation.timingFunction = CAMediaTimingFunction(name: "easeOut")
        
        //        `linear', `easeIn', `easeOut' and
        //        `easeInEaseOut' and `default'
        animation.removedOnCompletion = false
        animation.fillMode = kCAFillModeForwards
        
        animation.delegate = self
        animation.type = "rippleEffect"
        //        animation.subtype = kCATransitionFromTop
        self.view.layer.addAnimation(animation, forKey: "animation")
//        
        
        page += 1
//        let iSHDDEN = (page == strS.count - 1)
//
//        self.newPageBtn.hidden = iSHDDEN
//        self.bgeinBtn.hidden   = iSHDDEN ? false: true
//        UIView.animateWithDuration(0.5, animations: {
//            self.view.transform   = CGAffineTransformMake(-1, 0, 0, 1, 0, 0)
//            self.titleLbl.alpha   = 0
//            self.g_imgBgtp.alpha  = 0
//            self.g_imgBgbm.alpha  = 0
//            btn.alpha             = 0
//            self.bgeinBtn.alpha   = 0
//        }) { (_) in
//            self.view.transform   = CGAffineTransformIdentity
//            UIView.animateWithDuration(0.2, animations: {
//                btn.alpha             = 1
//                self.bgeinBtn.alpha   = 1
//                self.g_imgBgtp.alpha  = 1
//                self.g_imgBgbm.alpha  = 1
//                self.titleLbl.text    = ""
//                self.titleLbl.alpha   = 1
//                btn.enabled           = false
//            })
//        }
        starDescription(strS[page])
    }
    
    override func loadView() {
        super.loadView()
        upView()
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        starDescription(strS[page])
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(v)
        
        let pan = UIPanGestureRecognizer.init(target: self, action: #selector(self.panGestureCallback(_:)))
        self.view .addGestureRecognizer(pan)
    }
    
    func starDescription(str: String) {
        let thred = NSThread(target: self, selector: #selector(self.animationLabel(_:)), object: str)
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
            thred.start()
        }
    }
    
    @objc private func animationLabel(str: String) {
        var i = 0
        for _ in str.characters {
            let nstr = (str as NSString).substringWithRange(NSRange(location: 0, length: i + 1))
            self.performSelectorOnMainThread(#selector(self.refreshTitleLbl(_:)), withObject:nstr ,waitUntilDone: true)
            NSThread.sleepForTimeInterval(0.1)
            i += 1
        }
        newPageBtn.enabled = true
    }
    
    @objc private func refreshTitleLbl(str: String) {
        titleLbl.text = str
    }
    
    
    
    // MARK: Private
    private let strS = ["据点存在在世界各个角落，你必须入侵据点以获得特工装备。",
                        "能量遍布周围四处走走可以收集我们需要的能量",
                        "好了，特工，去占领更多的据点吧，让世界因你而不同！",
                        "为了尽快熟悉游戏，我们为您准备了虚拟环境中的新手引导训练，欢迎体验!"]
    
    private var page = 0
    
    private lazy var bgeinBtn: UIButton = UIButton(imgName: "guide_begin_0")
    
    private lazy var newPageBtn: UIButton = UIButton(imgName: "guide_newpage_0")
    
    private lazy var  g_imgBgtp: UIImageView = UIImageView(imgName: "guide_bg_00")
    
    private lazy var  g_imgBgbm: UIImageView = UIImageView(imgName: "guide_bg_01")
    
    private lazy var  titleLbl: UILabel = UILabel(font: 14, color: hexString("ffa21b"), preferredMaxW: 200)
}

extension GuideViewController {
    
    private func upView() {
        
        view.addSubview(titleLbl)
        view.addSubview(g_imgBgbm)
        view.addSubview(g_imgBgtp)
        view.addSubview(newPageBtn)
        view.addSubview(bgeinBtn)
        
        bgeinBtn.hidden = true
        newPageBtn.enabled = false
        g_imgBgtp.transform = CGAffineTransformMakeScale(3, 3)
        
        newPageBtn.addTarget(self, action: #selector(self.newPageButtonClick(_:)), forControlEvents: .TouchUpInside)
        //        bgeinBtn.addTarget(self, action: #selector(self.newPageButtonClick(_:)), forControlEvents: .TouchUpInside)
        //        print(self.view.height / 106 / 100)
        view.backgroundColor = UIColor.blackColor()
        //        view.backgroundColor = UIColor.hexStringToColor("f0f0f0", alpha: 0.9)
        
        titleLbl.snp_makeConstraints { (make) in
            make.left.equalTo(self.view).offset(self.view.width * 0.3)
            make.top.equalTo(self.view).offset(106)
        }
        
        g_imgBgtp.snp_makeConstraints { (make) in
            make.top.equalTo(self.view).offset(self.view.height * 0.45)
            make.left.equalTo(self.view).offset(self.view.width * 0.45)
        }
        
        g_imgBgbm.snp_makeConstraints { (make) in
            make.top.equalTo(self.view).offset(self.view.height * 0.5)
            make.left.equalTo(self.view).offset(self.view.width * 0.28)
        }
        
        newPageBtn.snp_makeConstraints { (make) in
            make.bottom.equalTo(self.view).offset(-(self.view.height * 0.15))
            make.left.equalTo(self.view).offset(self.view.width * 0.5 - 50)
        }
        
        bgeinBtn.snp_makeConstraints { (make) in
            make.top.equalTo(self.newPageBtn)
            make.left.equalTo(self.newPageBtn)
        }
    }
}

